<template>
  <div class="p-4">
    <el-card>
      <!-- 搜索和新增 -->
      <div class="mb-4 flex justify-between items-center">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索教师姓名"
          clearable
          @keyup.enter="fetchTeachers"
          style="width: 300px"
        />
        <div>
          <el-button type="primary" @click="openForm()">新增教师</el-button>
          <el-button @click="goBack">返回</el-button>
        </div>
      </div>

      <!-- 教师表格 -->
      <el-table
        :data="filteredTeachers"
        border
        v-loading="loading"
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无数据'"
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="studentName" label="学生名称" width="100" />
        <el-table-column prop="teachType" label="教师类型" width="100" />
        <el-table-column prop="className" label="班级" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="openForm(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹窗 -->
      <el-dialog
        :title="form.id ? '编辑教师' : '新增教师'"
        v-model="formVisible"
        width="500px"
        :before-close="() => (formVisible = false)"
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          status-icon
        >
          <el-form-item label="教师类型" prop="teachType">
            <el-input v-model="form.teachType" />
          </el-form-item>
          
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="班级" prop="className">
            <el-input v-model="form.className" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number
              v-model="form.age"
              :min="1"
              :max="150"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getTeacherList,
  addTeacher,
  updateTeacher,
  deleteTeacher,
} from "../api/teacherManage.js";
import { useRouter } from 'vue-router';

const router = useRouter();

function goBack() {
  router.back(); // 返回上一个页面
}


const loading = ref(false);
const formVisible = ref(false);
const formRef = ref(null);
const searchKeyword = ref("");

const teachers = ref([]);

function getEmptyForm() {
  return {
    id: null,
    teachType: "",
    name: "",
    className: "",
    age: null,
    sex: "",
    email: "",
    createTime: "",
    updateTime: "",
  };
}

const form = ref(getEmptyForm());

const rules = {
  teachType: [{ required: true, message: "请输入教师类型", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  className: [{ required: true, message: "请输入班级", trigger: "blur" }],
  age: [{ required: true, message: "请输入年龄", trigger: "change" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
    },
  ],
};

const filteredTeachers = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  if (!keyword) return teachers.value;
  return teachers.value.filter((t) => t.name?.toLowerCase().includes(keyword));
});

function openForm(teacher = null) {
  form.value = teacher ? { ...teacher } : getEmptyForm();
  formVisible.value = true;
}

async function fetchTeachers() {
  loading.value = true;
  try {
    const res = await getTeacherList();
    teachers.value = res?.data || [];
  } catch (err) {
    console.error("获取教师列表失败", err);
    ElMessage.error("获取教师列表失败");
  } finally {
    loading.value = false;
  }
}

async function handleSubmit() {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      if (form.value.id) {
        await updateTeacher(form.value);
        ElMessage.success("编辑成功");
      } else {
        await addTeacher(form.value);
        ElMessage.success("新增成功");
      }
      formVisible.value = false;
      await fetchTeachers();
    } catch (err) {
      console.error("保存失败", err);
      ElMessage.error("保存失败");
    }
  });
}

async function handleDelete(id) {
  ElMessageBox.confirm("确认删除该教师吗？", "提示", { type: "warning" })
    .then(async () => {
      try {
        await deleteTeacher(id);
        ElMessage.success("删除成功");
        await fetchTeachers();
      } catch (err) {
        console.error("删除失败", err);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
}

onMounted(fetchTeachers);
</script>

<style scoped>
.p-4 {
  padding: 16px;
}
.mb-4 {
  margin-bottom: 16px;
}
.flex {
  display: flex;
}
.justify-between {
  justify-content: space-between;
}
.items-center {
  align-items: center;
}
</style>
